package com.example.intelligentattendancesystem.controller;

import com.example.intelligentattendancesystem.mapping.HistoryMapping;
import com.example.intelligentattendancesystem.mapping.UserMapping;
import com.example.intelligentattendancesystem.mapping.WorkMapping;
import com.example.intelligentattendancesystem.pojo.History;
import com.example.intelligentattendancesystem.pojo.User;
import com.example.intelligentattendancesystem.pojo.Work;
import com.example.intelligentattendancesystem.service.FileUpService;
import com.example.intelligentattendancesystem.service.WorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.util.Date;
import java.util.List;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.WeekFields;
import java.util.Date;
import java.util.Locale;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
*
*@author
*@version 1.0
*@className FileUpController
*@since 1.0
*/
@RestController
@RequestMapping("smartAttendance/icon")
public class FileUpController {

    @Autowired
    FileUpService fileUpService;
    @Autowired
    HistoryMapping historyMapping;
    @Autowired
    UserMapping userMapping;
    @Autowired
    WorkMapping workMapping;

    @RequestMapping("upIcon")
    public String UpFile(@RequestPart(value = "file") MultipartFile img,int userId){
        String s = fileUpService.upFileService(img,userId);
        return s;
    }
    @GetMapping("/download/{fileName}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        // 指定文件所在的路径，这里假设文件存储在项目的 static/files 目录下
        Path filePath = Paths.get(fileName);
        Resource resource;
        try {
            // 加载文件作为 Resource
            resource = new org.springframework.core.io.UrlResource(filePath.toUri());
        } catch (IOException e) {
            throw new RuntimeException("无法加载文件: " + e.getMessage(), e);
        }

        // 设置响应头
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }
    @RequestMapping("/saveExcel")
    public String getExcel() throws ParseException {
        List<History> histories = historyMapping.selectAllHistory();

        if (histories.size() == 0) {
            return "no data";
        }else{
            // 创建Excel工作簿和工作表
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("HistoryData");

            // 将 historyList 数据写入工作表
            int rowNum = 0;
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue("用户昵称");
            row.createCell(1).setCellValue("班次开始时间");
            row.createCell(2).setCellValue("班次结束时间");
            row.createCell(3).setCellValue("签到时间");
            row.createCell(4).setCellValue("签退时间");
            row.createCell(5).setCellValue("签到位置");
            for (History history : histories) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = sdf.parse(history.getSignOutTime());
                // 将Date转换为LocalDateTime
                LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                // 获取该日期所在的周数
                int dayOfWeek = localDateTime.getDayOfWeek().getValue();
                Work work = workMapping.selectWorkByUserIdAndEndTeimeAndWeek(history.getUserId()+"", history.getSignOutTime().split(" ")[1], dayOfWeek + "");
                if(work == null){
                    continue;
                }
                row = sheet.createRow(rowNum++);
                User user = userMapping.selectUserByUserId(history.getUserId());
                row.createCell(0).setCellValue(user.getNick());
                row.createCell(1).setCellValue(work.getStartTime());
                row.createCell(2).setCellValue(work.getEndTime());
                row.createCell(3).setCellValue(history.getSignInTime());
                row.createCell(4).setCellValue(history.getSignOutTime());
                row.createCell(5).setCellValue(history.getSignPosition());
            }

            // 输出Excel文件
            File file = new File("history_data.xlsx");
            try {
                if (!file.exists()) {
                    // 创建新的Excel文件
                    file.createNewFile();
                    System.out.println("新文件已创建: history_data.xlsx");
                }
                // 将工作簿保存为Excel文件
                FileOutputStream fileOut = new FileOutputStream(file);
                workbook.write(fileOut);
                fileOut.close();
                workbook.close();
            } catch (IOException e) {
                throw new RuntimeException("无法保存Excel文件: " + e.getMessage(), e);
            }
            return "http://localhost:8080/smartAttendance/icon/download/"+"history_data.xlsx";
        }
    }
}
